import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Button, Card, Col, DatePicker, Divider, Form, Input, Modal, Row, Select, Table,} from 'antd';
import TableList from '@/components/TableList';

import styles from './../Out.less';
import {getReadableSize} from '@/utils/dsrsUtil';

const FormItem = Form.Item;
const {TextArea} = Input;
const {RangePicker} = DatePicker;
const processProgress = ['未处理', '处理中', '处理完成', '处理失败'];
const fileSource = ['个人文件', '共享申请', '接收文件', '外发申请', '其它','外接文件','自定义组文件申请'];
const formLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18},
};


@connect(({downloadModel, loading}) => ({
  downloadModel,
  loading: loading.models.downloadModel,
}))
@Form.create()
class DownloadUndo extends PureComponent {
  state = {
    auditModalVisible: false,
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    //详情
    strategyVisible: false,
    strategyData: {},
    downlStrategy: [],
  };

  columns = [
    {
      title: '文件名',
      dataIndex: 'fileNames',
      width: "30%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    // {
    //   title: '下载名称',
    //   dataIndex: 'downloadFileNames',
    // },
    {
      title: '文件大小',
      dataIndex: 'fileSize',
      render: (text, record) => {
        if (text) {
          return getReadableSize(text * 1024);
        } else {
          return '--'
        }
      },
    },
    {
      title: '文件来源',
      render(val) {
        return fileSource[val.fileSource];
      }
    },
    {
      title: '处理进度',
      render(val) {
        return processProgress[val.fileState];
      }
    }
    ,
    {
      title: '申请时间',
      render:
        val => <span>{moment(val.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>,
    }
    ,
    {
      title: '操作',
      render:
        (text, record) => (
          <Fragment>
            <a onClick={() => this.deleteData(text.id)}>删除</a>
            {text.fileState == 2 && (
              <Fragment>
                <Divider type="vertical"/>
                <a onClick={() => this.downFileCon(record)}>下载</a>
                <Divider type="vertical"/>
                <a onClick={() => this.strategyHandelVisible(true, text)}>管控策略</a>
              </Fragment>
            )}
          </Fragment>
        ),
    },
  ];


  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleDeleteData(id),
    });
  };


  strategyHandelVisible = (flag, record) => {
    this.setState({
      strategyVisible: !!flag,
      strategyData: record,
    });
    if (flag) {
      this.downloadStrategy(record.id);
    }
  };

  // 删除方法
  handleDeleteData(ids) {
    const {dispatch} = this.props;
    dispatch({
      type: 'downloadModel/filedownloadDelete',
      payload: {ids},
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
          this.filedownloadList();
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  downFileCon(record) {
    console.log(1111,record);     
    Modal.confirm({
      title: '下载',
      content: <Fragment>{record && record.fileSource ==3? (<Fragment>您确定要下载该文件吗？<br/>说明：下载至本地的文件名称将发生变化。</Fragment>):'您确定要下载该文件吗？'}</Fragment>,
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.downFile(record),
    });       
  }

  downFile(record) {
    const {dispatch} = this.props;
    const downloadExpireTime = record.downloadExpireTime;
    const nowTime = new Date().getTime();
    if (nowTime > downloadExpireTime && downloadExpireTime) {
      Modal.error({title: '操作失败', content: '已经超出有效期，不能下载'});
      return
    }


    // if (record.fileSource == 3) {
    //   //如果是外发，直接打开下载地址
    //   if (record.dowloadUrl) {
    //     window.open("//" + record.dowloadUrl);
    //     dispatch({
    //       type: 'downloadModel/setDownloaded',
    //       payload: {
    //         id: record.id,
    //       },
    //       callback: (res) => {
    //       },
    //     });
    //   } else {
    //     Modal.error({title: '操作失败', content: '下载地址为空，不能下载'});
    //     return;
    //   }
    // }

    dispatch({
      type: 'downloadModel/downloadFile',
      payload: {
        id: record.id,
      },
      callback: (res) => {
        // if(res.result == "ok") {
        //   window.open(res.msg,"_top");
        // }else {
        //   Modal.error({title: '操作失败',content: res.msg});
        // }
      },
    });
  }

  componentDidMount() {
    this.filedownloadList();
  }


  downloadStrategy(id) {
    const {dispatch} = this.props;
    dispatch({
      type: 'downloadModel/downloadStrategy',
      payload: {downloadId:id},
      callback: (res) => {
        if (res.result == "ok") {
          this.setState({
            downlStrategy: res.data || [],
          })
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }

  filedownloadList(data, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;

    const params = {
      fileNames: data && data.fileNames || '',
      fileSource: data ? data.fileSource : ' ',
      hasDownload: 0,//未下载
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    }
    dispatch({
      type: 'downloadModel/filedownloadList',
      payload: params,
      callback: (res) => {
        if (res.result == "ok") {
          Modal.success({title: res.msg});
        } else {
          Modal.error({title: '操作失败', content: res.msg});
        }
      },
    });
  }


  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {formValues} = this.state;
    this.filedownloadList(formValues, pagination.pageSize, pagination.current - 1);
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };


  //查询

  handleSearch = e => {
    e.preventDefault();
    const {dispatch, form} = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });
      this.filedownloadList(values)
    });
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="文件名">
              {getFieldDecorator('fileNames')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="文件来源">
              {/*0个人文件1接收文件2共享申请3外发申请99其他*/}
              {getFieldDecorator('fileSource')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="">--请选择--</Option>
                  <Option value={0}>个人文件</Option>
                  <Option value={1}>共享申请</Option>
                  <Option value={2}>接收文件</Option>
                  <Option value={3}>外发申请</Option>
                  <Option value={5}>外接文件</Option>
                  <Option value={6}>自定义组文件</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  batchDelete = (rows = []) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };


  render() {
    const {
      downloadModel: {data},
      loading,
    } = this.props;
    const {selectedRows, auditModalVisible, stepFormValues, strategyVisible, strategyData, downlStrategy} = this.state;
    const strategyMethods = {
      strategyHandelVisible: this.strategyHandelVisible,
    };
    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <div className={styles.tableListOperator}>
            {selectedRows.length > 0 && (
              <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
            )}
          </div>
          <TableList
            className={styles.tdPadding}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
            rowKey={record => record.id}
          />
        </div>
        {strategyData && strategyData.id ? (
          <Strategy {...strategyMethods} strategyVisible={strategyVisible} strategyData={strategyData}
                    loading={loading} downlStrategy={downlStrategy}/>
        ) : null}
      </Card>
    );
  }
}

class Strategy extends PureComponent {
  render() {
    const {strategyVisible, strategyHandelVisible, strategyData, downlStrategy, loading,} = this.props;
    const strategyRule = ['加解密', '扫描ID', '脱敏', 'PDF转换', '水印'];
    const columns = [
      {
        title: '文件名',
        dataIndex: 'fileName',
        key: 'fileName',
        ellipsis:true
      },
      {
        title: '原文件大小',
        dataIndex: 'fileSize',
        key: 'fileSize',
       ellipsis:true,
       render: (text, record) => {
          if (text) {
            return getReadableSize(text * 1024);
          } else {
            return '--'
          }
        },
      },
      {
        title: '管控策略',
        dataIndex: 'strategyRule',
        key: 'strategyRule',
        ellipsis:true,
      }, {
        title: '水印类型',
        dataIndex: 'watermarkType',
        key: 'watermarkType',
        ellipsis:true,
      }, {
        title: '水印内容',
        dataIndex: 'watermarkContent',
        key: 'watermarkContent',
       ellipsis:true,
      },
      // {
      //   title: '水印内容',
      //   dataIndex: 'watermarkContent',
      //   key: 'watermarkContent',
      //   width: '15%',
      //   render: (text) => (
      //     <div className={styles.colRemark} title={text}>
      //       {text}
      //     </div>
      //   )
      // },
      // {
      //   title: '脱敏字段',
      //   dataIndex: 'desensRule',
      //   key: 'desensRule',
      //   width: '15%',
      //   render: (text, record) => {
      //     if (text) {
      //       return <div className={styles.colRemark} title={text}>
      //         {text.map((v) => {
      //           return v
      //         }).join('、')
      //         }
      //       </div>
      //     }
      //   },
      // },
      // {
      //   title: '策略规则',
      //   dataIndex: 'strategyRule',
      //   key: 'strategyRule',
      //   width: '20%',
      //   render: (text, record) => {
      //     if (text) {
      //       return <div className={styles.colRemark} title={text}>
      //         {text.map((v) => {
      //           return strategyRule[v - 1]
      //         }).join('、')
      //         }
      //       </div>
      //     }
      //   },
      // },
    ];
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看管控策略"
        visible={strategyVisible}
        onOk={() => strategyHandelVisible()}
        onCancel={() => strategyHandelVisible()}
        footer={[
          <Button key="back" type="primary" onClick={() => strategyHandelVisible()}>返回</Button>
        ]}
      >

        <Table dataSource={downlStrategy}
               columns={columns}
               loading={loading}
               pagination={{
                 simple: false, defaultPageSize: 5,
                 total: downlStrategy.length,
                 pageSizeOptions: ['5', '10', '20', '30'],
                 showSizeChanger: true,
               }}/>
      </Modal>
    );
  }
}

export default DownloadUndo;
